//
//  Observable+HandyJSON.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2020/8/11.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import RxSwift
import Moya
import HandyJSON

/// 数据 转 模型
extension ObservableType where Element == Response {
    public func mapHandyJsonModel<T: HandyJSON>(
        _ url: String,
        _ type: T.Type,
       _ messageKey: String = "msg"
    ) -> Observable<T> {
        return flatMap { response -> Observable<T> in
            return Observable.just(response.mapHandyJsonModel(url, T.self, messageKey: messageKey))
        }
    }
}

extension Response {
    func mapHandyJsonModel<T: HandyJSON>(
        _ url: String,
        _ type: T.Type,
        messageKey: String = "msg"
    ) -> T {
        let jsonString = String.init(data: data, encoding: .utf8)
//        UserDefaults.standard.set(data, forKey: url + (UserInstance.userId ?? ""))
//        let dic: Dictionary = (jsonString?.getDictionaryFromJSONString()) ?? [:]
        var code: String = ""
//        if let c = dic["code"] as? Int {
//            code = "\(c)"
//        } else if let s = dic["code"] as? String {
//            code = s
//        }
//        let message = dic[messageKey] as? String ?? ""
//        let infoDic: [String: String] = ["code": code, "message": message]
//        UserDefaults.standard.set(infoDic, forKey: url + (UserInstance.userId ?? "") + REQUEST_DIC)
//        print("返回值：\n", dic.showJsonString)
//        if let modelT = JSONDeserializer<T>.deserializeFrom(json: jsonString) {
//            return modelT
//        }
        return JSONDeserializer<T>.deserializeFrom(json: "{\"\(messageKey)\":\"\("common.try")\"}")!
    }
}
